//
//  TopicViewController.swift
//  LaiLang
//
//  Created by David on 2017/2/25.
//  Copyright © 2017年 David. All rights reserved.
//

import UIKit

class TopicViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var _currentTab = 0
    
    var seletedTabIndex:Int{
        get{
            return _currentTab
        }
        set(c){
            _currentTab = c
            
            
            tabbarTableView.reloadData()
            
            var shouldShowWidth:CGFloat = 0.0
            if tabItems != nil {
                for i in 0..<c {
                    let catInfo = tabItems?.object(at: i) as? NSDictionary
                    
                    let catName = catInfo?.object(forKey: "name") as? String
                    
                    if catName != nil{
                        shouldShowWidth += (catName! as NSString).boundingRect(with: CGSize(width: CGFloat(MAXFLOAT), height: 36), options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName : UIFont.systemFont(ofSize: 14)], context: nil).width + 32
                    }
                    
                }
                if tabbarTableView.contentOffset.y > shouldShowWidth{
                    tabbarTableView.setContentOffset(CGPoint(x: 0, y: shouldShowWidth), animated: true)
                }else if tabbarTableView.contentOffset.y < shouldShowWidth - view.bounds.width {
                    tabbarTableView.setContentOffset(CGPoint(x: 0, y: shouldShowWidth), animated: true)
                }
                
            }
            
            
        }
    }
    
    //    convenience init(tab: Int, tabItems: [String]?){
    //        self.init()
    //        self.tabItems = tabItems as NSArray?
    //        _currentTab = tab
    //    }
    
    convenience init(tab: Int, tabItems: NSArray?){
        self.init()
        self.tabItems = tabItems
        _currentTab = tab
    }
    
    var tabItems: NSArray?
    
    var tabbarTableView: UITableView!
    var tabScrollView: UIScrollView!
    
    var tableViewInTab: [UITableView]!
    
    var topicSearchInput: UITextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.groupTableViewBackground
        let navbar = LLAdaptHideNavBar(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 64), title: "话题", navigator: navigationController)
        
        tabbarTableView = UITableView(frame: CGRect(x: 0, y: 64, width: 36, height: view.bounds.width))
        tabbarTableView.tag = 438
        tabbarTableView.transform = CGAffineTransform(rotationAngle: CGFloat(-Double.pi/2))
        tabbarTableView.center = CGPoint(x: view.center.x, y: 64 + 18)
        
        tabbarTableView.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: 36, height: 36))
        tabbarTableView.separatorStyle = .none
        tabbarTableView.showsVerticalScrollIndicator = false
        
        tabbarTableView.delegate = self
        tabbarTableView.dataSource = self
        view.addSubview(tabbarTableView)
        
        tabScrollView = UIScrollView(frame: CGRect(x: 0, y: 100, width: view.frame.width, height: view.frame.height - 100))
        tabScrollView.tag = 2358
        tabScrollView.delegate = self
        tabScrollView.alwaysBounceHorizontal = true
        tabScrollView.isPagingEnabled = true
        tabScrollView.showsHorizontalScrollIndicator = false
        view.addSubview(tabScrollView)
        
        tableViewInTab = []
        if tabItems != nil {
            tabScrollView.contentSize = CGSize(width: tabScrollView.frame.width * CGFloat(tabItems!.count), height: tabScrollView.frame.height)
            let stackView = UIStackView(frame: CGRect(x: 0, y: 0, width: tabScrollView.frame.width * CGFloat(tabItems!.count), height: tabScrollView.frame.height))
            stackView.axis = .horizontal
            stackView.distribution = .fillEqually
            for i in 0..<tabItems!.count{
                
                let tableView = UITableView(frame: CGRect(x: 0, y: 0, width: tabScrollView.frame.width, height: tabScrollView.frame.height))//, style: .grouped
                tableView.tag = 700 + i
                tableView.delegate = self
                tableView.dataSource = self
                tableView.backgroundColor = UIColor.groupTableViewBackground
                tableView.tableFooterView = UIView(frame: CGRect.zero)
//                let aView = UILabel(frame: CGRect(x: 16, y: 100, width: tabScrollView.frame.width - 32, height: 20))
//                aView.textAlignment = .center
//                aView.text = "\(i)"
//                tableView.addSubview(aView)
                
                stackView.addArrangedSubview(tableView)
                tableViewInTab.append(tableView)
                
                if i == 2{
                    tableView.keyboardDismissMode = .onDrag
                }
            }
            tabScrollView.addSubview(stackView)
        }
        
        seletedTabIndex = _currentTab
        tabScrollView.setContentOffset(CGPoint(x: tabScrollView.frame.width * CGFloat(_currentTab), y: 0), animated: true)
        
        view.addSubview(navbar)
        
        topicSearchInput = UITextField(frame: CGRect(x: 8, y: 0, width: view.bounds.width - 32, height: 28))
//        topicSearchInput.backgroundColor = UIColor.white
//        topicSearchInput.textColor = UIColor.lightGray
        topicSearchInput.placeholder = "搜索感兴趣的话题"
        topicSearchInput.returnKeyType = .search
//        topicSearchInput.layer.cornerRadius = 4
        topicSearchInput.font = UIFont.systemFont(ofSize: 14)
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        switch scrollView.tag {
        case tabScrollView.tag:
            seletedTabIndex = Int(scrollView.contentOffset.x / tabScrollView.frame.width)
            
            break
        default:
            
            break
        }
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        if tableView.tag / 100 == 7{
            let tabTag = tableView.tag - 700
            if tabTag == 2{
                return 2
            }
        }
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch tableView.tag {
        case tabbarTableView.tag:
            if tabItems != nil {
                return tabItems!.count
            }
            return 0
        default:
            if tableView.tag / 100 == 7{
                let tabTag = tableView.tag - 700
                switch tabTag {
                case 0:
                    return 1
                case 1:
                    return 1
                case 2:
                    if section == 0{
                        return 2
                    }
                    return 1
                default:
                    break
                }
            }
            return 0
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        switch tableView.tag {
        case tabbarTableView.tag:
            if tabItems != nil {
//                let catInfo = tabItems?.object(at: indexPath.row) as? NSDictionary
                
                let catName = tabItems?.object(at: indexPath.row) as? String
                
                if catName != nil{
                    return (catName! as NSString).boundingRect(with: CGSize(width: CGFloat(MAXFLOAT), height: 36), options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName : UIFont.systemFont(ofSize: 14)], context: nil).width + 32
                }
                
            }
            return 44
        default:
            if tableView.tag / 100 == 7{
                let tabTag = tableView.tag - 700
                switch tabTag {
                case 0:
                    break
                case 1:
                    return 72
                case 2:
                    if indexPath.section == 0 && indexPath.row == 1{
                        return 160
                    }
                    if indexPath.section == 1 && indexPath.row == 0{
                        return 80
                    }
                    break
                default:
                    break
                }
            }
            return 44
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .default, reuseIdentifier: "item")
        switch tableView.tag {
        case tabbarTableView.tag:
            cell.selectionStyle = .none
            if tabItems != nil {
//                let catInfo = tabItems?.object(at: indexPath.row) as? NSDictionary
                
                let titleStr = tabItems?.object(at: indexPath.row) as? String
                var titleWidth:CGFloat = 0.0
                if titleStr != nil{
                    titleWidth = (titleStr! as NSString).boundingRect(with: CGSize(width: CGFloat(MAXFLOAT), height: 36), options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName : UIFont.systemFont(ofSize: 14)], context: nil).width + 32
                }
                
                
                let titleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: titleWidth, height: 36))
                titleLabel.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi/2))
                titleLabel.center = CGPoint(x: 18, y: titleWidth/2)
                titleLabel.textAlignment = .center
                cell.addSubview(titleLabel)
                
                titleLabel.font = UIFont.systemFont(ofSize: 14)
                titleLabel.text = titleStr
                
                if indexPath.row == seletedTabIndex {
                    let seletedBar = UIView(frame: CGRect(x: 0, y: 0, width: 2, height: titleWidth))
                    seletedBar.backgroundColor = themeColor
                    cell.addSubview(seletedBar)
                }
            }
            break
        default:
            if tableView.tag / 100 == 7{
                let tabTag = tableView.tag - 700
                switch tabTag {
                case 0:
                    break
                case 1:
                    // MARK: 热门话题
                    
                    let imageView = UIImageView(frame: CGRect(x: 16, y: 8, width: 56, height: 56))
                    imageView.backgroundColor = UIColor.lightGray
                    cell.addSubview(imageView)
                    
                    let titleLabel = UILabel(frame: CGRect(x: 80, y: 8, width: view.bounds.width - 96, height: 16))
                    titleLabel.text = "#话题#"
                    titleLabel.font = UIFont.systemFont(ofSize: 16)
                    cell.addSubview(titleLabel)
                    
                    let detailLabe = UILabel(frame: CGRect(x: 80, y: 30, width: view.bounds.width - 96, height: 16))
                    detailLabe.text = "xxxxxxxxxxxxxx"
                    detailLabe.textColor = UIColor.lightGray
                    detailLabe.font = UIFont.systemFont(ofSize: 12)
                    cell.addSubview(detailLabe)
                    
                    let infoLabel = UILabel(frame: CGRect(x: 80, y: 48, width: view.bounds.width - 96, height: 16))
                    infoLabel.text = "粉丝: ___  讨论: ___"
                    infoLabel.textColor = UIColor.lightGray
                    infoLabel.font = UIFont.systemFont(ofSize: 12)
                    cell.addSubview(infoLabel)
                    
                    break
                case 2:
                    // MARK: 更多话题
                    
                    switch indexPath.section {
                    case 0:
                        cell.selectionStyle = .none
                        switch indexPath.row {
                        case 0:
                            cell.backgroundColor = UIColor.lightGray
                            
                            let searchBarBG = UIView(frame: CGRect(x: 8, y: 8, width: view.bounds.width - 16, height: 28))
                            searchBarBG.layer.cornerRadius = 4
                            searchBarBG.backgroundColor = UIColor.white
                            searchBarBG.addSubview(topicSearchInput)
                            
                            cell.addSubview(searchBarBG)
                            break
                        case 1:
                            let titleLabel = UILabel(frame: CGRect(x: 16, y: 8, width: view.bounds.width - 32, height: 20))
                            titleLabel.text = "优质话题"
                            cell.addSubview(titleLabel)
                            
                            
                            let scrollView = UIScrollView(frame: CGRect(x: 0, y: 36, width: view.bounds.width, height: 124))
                            scrollView.alwaysBounceHorizontal = true
                            cell.addSubview(scrollView)
                            
                            let itemCount = 10
                            
                            scrollView.contentSize = CGSize(width: 100*CGFloat(itemCount), height: 124)
                            
                            let stackView = UIStackView(frame: CGRect(x: 0, y: 0, width: 100*CGFloat(itemCount), height: 100))
                            stackView.axis = .horizontal
                            stackView.distribution = .fillEqually
                            scrollView.addSubview(stackView)
                            
                            for i in 0..<itemCount  {
                                let topicView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
                                let btn = UIButton(frame: CGRect(x: 16, y: 0, width: 68, height: 68))
                                btn.backgroundColor = UIColor.lightGray
                                topicView.addSubview(btn)
                                
                                let topicTitle = UILabel(frame: CGRect(x: 0, y: 72, width: 100, height: 24))
                                topicTitle.text = "话题\(i)"
                                topicTitle.textAlignment = .center
                                topicTitle.font = UIFont.systemFont(ofSize: 16)
                                topicView.addSubview(topicTitle)
                                
                                stackView.addArrangedSubview(topicView)
                            }
                            break
                        default:
                            break
                        }
                    case 1:
                        break
                    default:
                        break
                    }
                    break
                default:
                    break
                }
            }
            break
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        switch tableView.tag {
        case tabbarTableView.tag:
            seletedTabIndex = indexPath.row
            tabScrollView.setContentOffset(CGPoint(x: tabScrollView.frame.width * CGFloat(_currentTab), y: 0), animated: true)
            break
        default:
            if tableView.tag / 100 == 7{
                let tabTag = tableView.tag - 700
                switch tabTag {
                case 0:
                    break
                case 1:
                    tableView.deselectRow(at: indexPath, animated: true)
                    let topicDetailVC = TopicDetailViewController()
                    hidesBottomBarWhenPushed = true
                    navigationController?.pushViewController(topicDetailVC, animated: true)
                    break
                case 2:
                    break
                default:
                    break
                }
            }
            break
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
